import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.List;


public class Dom4j_ {
/*
* 演示如何加载xml文件*/
    @Test
    public void load() throws DocumentException, IOException {
        //解析器
        SAXReader reader = new SAXReader();
//老师的代码技巧->debug 看看 document 对象的属性
//分析了 document 对象的底层结构
        Document document = reader.read(new File("src/students.xml"));
        System.out.println(document);
        //遍历roorElement
        Element rootElement = document.getRootElement();
        List<Element> students = rootElement.elements("student");
        for (Element student : students) {
            Element name = student.element("name");
            Element age = student.element("age");
            Element gender = student.element("gender");
            Element resume = student.element("resume");
            System.out.println("学生信息 姓名:"+name.getText()+" 年龄:"+age.getText()
            +" 性别："+gender.getText()+" resume:"+resume.getText());
        }
//获取单个用户
        List<Element> students01 = document.getRootElement().elements("student");
        Element student01 = students01.get(1);
        System.out.println("该学生信息是"+student01.element("name").getText()
                +student01.element("age").getText()
                +student01.element("gender").getText()
                +student01.element("resume").getText());
        //获取student的id
        System.out.println(student01.attributeValue("id"));
        Element newStu = DocumentHelper.createElement("student");
        newStu.addAttribute("id","04");
        Element newStu_name = DocumentHelper.createElement("name");
        newStu_name.setText("杨过");
        Element newStu_age = DocumentHelper.createElement("age");
        newStu_age.setText("12");
        Element newStu_gender = DocumentHelper.createElement("gender");
        newStu_gender.setText("男");
        Element newStu_resume = DocumentHelper.createElement("resume");
        newStu_resume.setText("古墓派弟子");
        newStu.add(newStu_name);
        newStu.add(newStu_age);
        newStu.add(newStu_gender);
        newStu.add(newStu_resume);
        document.getRootElement().add(newStu);
        //直接输出会出现乱码
        OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
        prettyPrint.setEncoding("utf-8");
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File("src/students.xml")), prettyPrint);
        xmlWriter.write(document);
        xmlWriter.close();


    }


}
